package com.ccys.cms.service.masterData.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.masterData.PricingTimingService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.cache.UserUtil;
import com.ccys.db.dto.masterData.PricingTimingIdDto;
import com.ccys.db.dto.masterData.PricingTimingPageQueryDto;
import com.ccys.db.dto.masterData.PricingTimingSaveDto;
import com.ccys.db.entity.TblAccount;
import com.ccys.db.entity.TblPricingTiming;
import com.ccys.db.mapper.TblPricingTimingMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.masterData.PricingTimingPageQueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 问诊价格设置实现类
 * @author: ZhangJingCan
 * @create: 2023-12-13 17:57
 **/

@Service
public class PricingTimingServiceImpl extends BaseServiceImpl<TblPricingTiming> implements PricingTimingService {

    @Resource
    private TblPricingTimingMapper tblPricingTimingMapper;

    /**
     * 用于保存修改状态日志
     */
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult savePricingTiming(PricingTimingSaveDto dto) {
        //无论新增还是修改都要校验的几个字段
        if (ObjectUtil.isEmpty(dto.getCountryId()) || ObjectUtil.isEmpty(dto.getType())
                || ObjectUtil.isEmpty(dto.getName()) || ObjectUtil.isEmpty(dto.getOfficeType())
                || ObjectUtil.isEmpty(dto.getValue()) || ObjectUtil.isEmpty(dto.getTimeStart()) || ObjectUtil.isEmpty(dto.getTimeEnd())) {
            return ResponseResult.error("Parameter Error!");
        }

        //需要校验 - Consultation hour:0 normal,1 special
        if (dto.getType().equals(1)) {
            //校验date字段是否有值 - 没值则返回错误信息
            if (ObjectUtil.isEmpty(dto.getDate())) {
                return ResponseResult.error("Parameter Error!");
            }

            //校验时间格式 - 以及结束时间不能小于开始时间
            // 创建时间格式化器，用于解析时间字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
            try {
                // 解析字符串为LocalTime对象
                LocalTime startTime = LocalTime.parse(dto.getTimeStart(), formatter);
                LocalTime endTime = LocalTime.parse(dto.getTimeEnd(), formatter);
                // 比较两个时间
                if (endTime.isBefore(startTime)) {
                    // 如果endTime时间早于startTime时间，抛出异常
                    return ResponseResult.error("The end time cannot be lower than the start time!");
                }
            } catch (DateTimeParseException e) {
                // 如果解析时间失败，抛出异常
                return ResponseResult.error("Time format error, please check if the time format is HH:mm");
            }
        }

        //新增/修改
        return ResponseResult.update(this.insertOrUpdate(dto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deletePricingTiming(PricingTimingIdDto dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备参数进行软删除
        TblPricingTiming timing = new TblPricingTiming();
        timing.setId(dto.getId());
        timing.setDelFlag(1);
        //进行操作并返回是否成功
        if (tblPricingTimingMapper.updateByPrimaryKeySelective(timing) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    public ResponseResult<PageInfo<PricingTimingPageQueryVo>, Object> findPagePricingTiming(PricingTimingPageQueryDto dto) {
        if (ObjectUtil.isEmpty(dto.getCountryId())){
            //如果未传入国家ID
            TblAccount account = UserUtil.getCurLoginAccount();
            if (ObjectUtil.isEmpty(account)){
                return ResponseResult.error("Not Logged In");
            }
            dto.setAccountId(account.getId());
        }
        dto.setType(Optional.ofNullable(dto.getType()).filter(t -> t > -1 && t < 2).orElse(null));
        dto.setOfficeType(Optional.ofNullable(dto.getOfficeType()).filter(o -> o > -1 && o < 3).orElse(null));
        PageDto.startPage();
        List<PricingTimingPageQueryVo> list = tblPricingTimingMapper.findPage(dto);
        PageInfo<PricingTimingPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updatePricingTimingStatus(PricingTimingIdDto dto) {
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        TblPricingTiming timing = new TblPricingTiming();
        timing.setId(dto.getId());
        timing.setStatus(dto.getStatus());
        if (tblPricingTimingMapper.updateByPrimaryKeySelective(timing) > 0) {
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }
}
